﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace HangFire.Job
{
    /// <summary>
    /// 获取必应图片地址
    /// </summary>
    public class BingImgJob
    {
        /// <summary>
        /// 获取必应图片地址
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentImg(string typeStr)
        {
            string url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN";
            using (HttpWebResponse response = CreateGetHttpResponse(url)) {
                using (Stream stream = response.GetResponseStream())   //获取响应的字符串流
            {
                    using (StreamReader sr = new StreamReader(stream))//创建一个stream读取流
                    {
                        string jsonText = sr.ReadToEnd();
                        JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
                        if (!jo.ContainsKey("images")) {
                            return $"【{typeStr}】获取图片信息失败！";
                        }
                        JArray images = (JArray)jo["images"];
                        List<string> saveList = new List<string>();
                        if (images.First != null) {
                            return $"【{typeStr}】图片地址：https://cn.bing.com{images.First["url"]}";
                        }
                    }
                }
            }            
            return $"【{typeStr}】获取图片信息失败！";
        }

        /// <summary>
        /// 获取HttpWebResponse，记得要关闭
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static HttpWebResponse CreateGetHttpResponse(string url)
        {
            HttpWebRequest request = null;

            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                return true; //总是接受
            });
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version11;
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.62";
            return request.GetResponse() as HttpWebResponse;
        }
    }
}